package com.example.routelink.gateway.filter;

import cn.dev33.satoken.secure.SaBase64Util;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.hutool.core.util.URLUtil;
import com.example.routelink.gateway.entity.ResultEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class DecryptRequestUrlFilterGatewayFilterFactory extends BaseFilter<DecryptRequestUrlFilterGatewayFilterFactory.Config> implements Ordered {
    public DecryptRequestUrlFilterGatewayFilterFactory() {
        super(DecryptRequestUrlFilterGatewayFilterFactory.Config.class);
    }
    private final String filterName = "解密URL";

    @Override
    public GatewayFilter apply(DecryptRequestUrlFilterGatewayFilterFactory.Config config) {
        return (exchange, chain) -> {
            long startTime = System.currentTimeMillis();
            ServerHttpRequest request = exchange.getRequest();
            URI newUri;
            String newUrl;
            try {
                Map<String, String> encryptionMap = exchange.getRequest().getQueryParams().toSingleValueMap();
                HashMap<String, String> decryptMap = new HashMap<>();
                for (Map.Entry<String, String> entry : encryptionMap.entrySet()) {
                    if (isGatewayCustom(entry.getKey()) || "sign".equals(entry.getKey()) || "nonce".equals(entry.getKey()) || "timestamp".equals(entry.getKey())) {
                        decryptMap.put(entry.getKey(), entry.getValue());
                    } else {
                        decryptMap.put(entry.getKey(), SaSecureUtil.aesDecrypt(config.secretKey, SaBase64Util.decode(entry.getValue())));
                    }
                }
                newUrl = exchange.getRequest().getURI().toString().split("\\?")[0];
                newUrl = newUrl + "?" + URLUtil.buildQuery(decryptMap, StandardCharsets.UTF_8);
                newUri = URLUtil.toURI(newUrl);
            } catch (Exception e) {
                log.error("解密异常", e);
                return response(exchange, ResultEnum.ErrEncryption);
            }
//            log.info("[过滤器-解密] 校验通过，解密之后uri {} ", newUrl);
            writeLog(filterName, startTime, "校验通过,解密之后uri {} ", newUrl);
            ServerHttpRequest mutableReq = request.mutate()
                    .uri(newUri)
                    .build();
            ServerWebExchange.Builder mutableExchange = exchange.mutate().request(mutableReq);
            return chain.filter(mutableExchange.build());
        };
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }


    @Data
    public static class Config {
        private String type;
        private String secretKey;
    }
}
